#include "ItemContainer.h"
#include "Item.h"
#include "Game.h"
#include "ObjectDatabase.h"
#include "StringLib.h"
#include "Renderer.h"
#include "Character.h"
#include "Util.h"
#include "Load.h"

ItemContainer::ItemContainer(ItemContainerType type, LockType lockType, bool locked) : LockedObstacle(GT_OB_ITEMCONTAINER, lockType, locked) {
	m_types[TH_ITEMCONTAINER_TYPE] = type;
	m_blocking = false;
	const ItemContainerInfo& info = g_objectDatabase->getItemContainerInfo(type);
	m_items = new std::list<Item*>();
}

ItemContainer::ItemContainer(std::ifstream& file) : LockedObstacle(GT_OB_ITEMCONTAINER, file) {
	m_blocking = false;
	m_items = new std::list<Item*>();
	int* tokens = Util::intSplit(file);
	m_types[TH_ITEMCONTAINER_TYPE] = tokens[0];
	for(int i = 0; i < tokens[1]; i++)
		addItem(Load::loadItem(file));
	delete[] tokens;
}

ItemContainer::~ItemContainer() {
	for(std::list<Item*>::iterator iter = m_items->begin(); iter != m_items->end(); iter++) {
		delete *iter;
	}
	delete m_items;
}

void ItemContainer::save(std::ofstream& file) const {
	file << getType(TH_GENERIC_TYPE) << "\n";
	LockedObstacle::save(file);
	file << getType(TH_ITEMCONTAINER_TYPE) << " " << m_items->size() << "\n";
	for(std::list<Item*>::const_iterator iter = m_items->begin(); iter != m_items->end(); iter++)
		(*iter)->save(file);
}

void ItemContainer::addItem(Item* item) {
	Character::insertItem(m_items, item);
	item->setParentList(m_items);
}

void ItemContainer::removeItem(Item* item) {
	m_items->remove(item);
}

void ItemContainer::render(float x, float y) {
	g_renderer->render(*this, x, y);
}

std::string ItemContainer::getName() const {
	if(m_lockType != LT_NONE)
		return std::string(m_locked ? "locked " : "unlocked ") + Obstacle::getName();
	return Obstacle::getName();
}

void ItemContainer::logDetails(TextLog& log) const {
	Obstacle::logDetails(log);
	log.addBlankLine();
	if(m_lockType != LT_NONE) {
		log.addLine(g_stringLib->getTextString(ST_IC_LOCK_TYPE, Obstacle::getName().c_str(), g_stringLib->getMiscString(MST_LOCK, m_lockType).c_str()));
		log.addLine(g_stringLib->getTextString(ST_IC_LOCKED, Obstacle::getName().c_str(), std::string(m_locked ? "locked" : "unlocked").c_str()));
	}
}
